import time
import RPi.GPIO as GPIO

X=[16,20,21]
Y=[6,13,19,26]
		
def keyboard_init():
	GPIO.cleanup()
	GPIO.setmode(GPIO.BCM)
	for i in range(0,3):
		GPIO.setup(X[i],GPIO.OUT)
		GPIO.output(X[i],GPIO.LOW)
		
	for j in range(0,4):
		GPIO.setup(Y[j],GPIO.IN,pull_up_down=GPIO.PUD_UP)#上拉输入
		

def keyboard_decode():
	keynums=0
	#第一列
	GPIO.output(X[0],GPIO.LOW)
	GPIO.output(X[1],GPIO.HIGH)
	GPIO.output(X[2],GPIO.HIGH)
	for i in range(len(Y)):
		if GPIO.input(Y[i])==GPIO.LOW:
			keynums=i+1
	
	#第二列
	GPIO.output(X[0],GPIO.HIGH)
	GPIO.output(X[1],GPIO.LOW)
	GPIO.output(X[2],GPIO.HIGH)	
	for i in range(len(Y)):
		if GPIO.input(Y[i])==GPIO.LOW:
			keynums=i+5
	#第三列
	GPIO.output(X[0],GPIO.HIGH)
	GPIO.output(X[1],GPIO.HIGH)
	GPIO.output(X[2],GPIO.LOW)
	for i in range(len(Y)):
		if GPIO.input(Y[i])==GPIO.LOW:
			keynums=i+9
	
	return keynums



if __name__=='__main__':
	keyboard_init()
	while True:
		print(keyboard_decode())
	